﻿using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Core.Repository;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Service.LogApp;
using DongFangGuoKai.WMSPlatform.Service.OutboundOrderDetail;
using DongFangGuoKai.WMSPlatform.Service.OutboundOrderDetail.DTO;
using DongFangGuoKai.WMSPlatform.WebApi.Utility.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Serilog;
using StackExchange.Redis;
using static Dm.net.buffer.ByteArrayBuffer;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers.OrderOutbound
{
    /// <summary>
    /// 出库
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TShippingOrderDetailController : ApiBaseController
    {
        private readonly ITOutboundOrderDetailService tOutboundOrderDetailService;
        private readonly IRepository<TShippingOrderDetail> shippingOrderrepost;
        private readonly IRepository<TShippingLockCell> shippinglockcellrepost;
        private readonly ILogger<TShippingOrderDetailController> shippingorderlogger;
        private readonly IRepository<TInstruct> instructrepost;
        private readonly ILogService interfaceLogService;

        private readonly IRepository<TQueceRecard> QueceRepo;


        public TShippingOrderDetailController(ITOutboundOrderDetailService tOutboundOrderDetailService,
            IRepository<TShippingOrderDetail> shippingOrderrepost,
            IRepository<TShippingLockCell> shippinglockcellrepost,
            ILogger<TShippingOrderDetailController> shippingorderlogger,
            IRepository<TInstruct> instructrepost,
            ILogService interfaceLogService
,
            IRepository<TQueceRecard> queceRepo) : base(interfaceLogService)
        {
            this.tOutboundOrderDetailService = tOutboundOrderDetailService;
            this.shippingOrderrepost = shippingOrderrepost;
            this.shippinglockcellrepost = shippinglockcellrepost;
            this.shippingorderlogger = shippingorderlogger;
            this.instructrepost = instructrepost;
            this.interfaceLogService = interfaceLogService;
            QueceRepo = queceRepo;
        }
        /* 弃用
        [HttpPost]
        public IActionResult SubmitOutboudOrder(SubmitOutListDTONoNet OrderDTO)
        {
            string message;
            try
            {
                var resOut = tOutboundOrderDetailService.ChukuMsg(OrderDTO, out message);
               
                if (resOut)
                {
                    return Ok();
                }
                else
                {
                    return Ok();
                }
            }
            catch (Exception ex)
            {
                
                return Ok();
            }
        }
        */

        /// <summary>
        /// 查询出库单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetShippingOrderList(int pageIndex, int pageSize)
        {
            var list = shippingOrderrepost.GetList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            List<GetChukuDanDTO> resList = new List<GetChukuDanDTO>();
            if (list != null)
            {
                foreach (var item in list)
                {
                    var lockcells = shippinglockcellrepost.GetList(s => s.OrderId == item.Id);
                    resList.Add(new GetChukuDanDTO()
                    {
                        OrderSn = item.OrderSn,
                        OutBoundNo = item.OutBoundNo,
                        CreateTime = item.CreateDate,

                        CreateUserName = item.CreateUserName,
                        AuditUserName = item.AuditUserName,
                        shippingOrders = lockcells,
                    });
                }
                return Success(resList);
            }
            return Failed("查询失败！");
        }

        /// <summary>
        /// 执行出库
        /// </summary>
        /// <param name="OutBoundNo"></param>
        /// <returns></returns>
        //[HttpPost]
        //public IActionResult ExecuteOutBound(string OutBoundNo)
        //{
        //    string errorMsg = string.Empty;
        //    TInterfaceLog log;
        //   var IsOk = tOutboundOrderDetailService.ExecuteOutBound(OutBoundNo, out errorMsg);

        //    CreateInterfaceLog("执行出库任务", "/api/TShippingOrderDetail/ExecuteOutBound", 2, OutBoundNo, out log);
        //    if (IsOk)
        //    {
        //        shippingorderlogger.LogInformation("方法名：ExecuteOutBound, 信息：" + errorMsg + "参数：" + OutBoundNo);
        //        return Success(errorMsg);
        //    }
        //    shippingorderlogger.LogError("方法名：ExecuteOutBound , 错误信息：" + errorMsg + "参数：" + OutBoundNo);
        //    return Failed(errorMsg);
        //}

        /// <summary>
        /// 样品到输送线
        /// </summary>
        /// <param name="reqCode"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult SampleToConveyor(string reqCode)
        {
            Guid guid;
            TInterfaceLog log;
            CreateInterfaceLog("样品到输送线", "/api/TShippingOrderDetail/SampleToConveyor", 1, reqCode, out log);
            if (!Guid.TryParse(reqCode, out guid))
            {
                return Failed("Guid不对");
            }
            var instruct = instructrepost.Get(i => i.BusinessGroupId == guid);
            if (instruct == null)
            {
                shippingorderlogger.LogError("方法名：SampleToConveyor 错误信息：未查询到对应指令" + "参数：" + reqCode);
                return Failed("未查询到对应指令");
            }
            string errorMsg = string.Empty;
            var IsOk = tOutboundOrderDetailService.SampleToConveyor(instruct, out errorMsg);

            if (IsOk)
            {
                shippingorderlogger.LogInformation("方法名：SampleToConveyor 信息：" + errorMsg + "参数：" + reqCode);

                return Success(errorMsg);
            }
            shippingorderlogger.LogError("方法名：SampleToConveyor 错误信息：" + errorMsg + "参数：" + reqCode);
            return Failed(errorMsg);
        }
        /// <summary>
        /// 添加出库单
        /// </summary>
        /// <param name="addOutBoundOrder"></param>
        /// <returns></returns>
        [HttpPost]
        [TypeFilter(typeof(CtmLogActionAsyncFilterAttribute))]
        public IActionResult AddOutboundOrders(AddOutBoundOrder addOutBoundOrder)
        {
            string errorMsg = string.Empty;
            TInterfaceLog log;
            CreateInterfaceLog("Lims下传出库单", "/api/TShippingOrderDetail/AddOutboundOrders", 2, addOutBoundOrder.ToJson(), out log);
            var IsOk = tOutboundOrderDetailService.AddOutboundOrders(addOutBoundOrder, out errorMsg);
            //AddQueceWindowCode(addOutBoundOrder.SampleInfo.FirstOrDefault()?.WindowCode, addOutBoundOrder.OrderNo);
            if (IsOk)
            {
                shippingorderlogger.LogInformation("方法名：AddOutboundOrders 信息：" + errorMsg + "参数：" + addOutBoundOrder.ToJson());
                return Success(errorMsg);
            }

            shippingorderlogger.LogError("方法名：AddOutboundOrders 错误信息：" + errorMsg + "参数：" + addOutBoundOrder.ToJson());
            return Failed(errorMsg);
        }

        [NonAction]
        private void AddQueceWindowCode(string code, string orderNo)
        {
            try
            {
               
                var quece = QueceRepo.Get(t => t.BillNO == orderNo && t.Status == 0);
                if (quece == null)
                {
                    shippingorderlogger.LogError($"出库单下发，委托单未进行排队：{orderNo}");
                    return;
                }

                quece.CounterNo = code;
                QueceRepo.Update(quece);


            }
            catch (Exception ex)
            {
                shippingorderlogger.LogError(ex.Message);

            }

        }
    }
}
